package com.ysd.lis.controller;

import cn.hutool.core.io.FileUtil;
import com.ysd.common.Result;
import com.ysd.lis.annotation.LogDetail;
import com.ysd.lis.aspect.OperationType;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.util.PropertySlash;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.function.Supplier;

/**
 * @author LuoXS
 * @date 2024/5/10
 * version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController extends BaseController {

    private static final int MAX_POST_SIZE = 20 * 1024 * 1024;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    @LogDetail(operationType = OperationType.UPDATE, module = "上传检验图片")
    public Result uploadSignatureFile(@RequestParam(value = "file") MultipartFile file) throws IOException {
        if (file == null) {
            return Result.fail("文件不能为空");
        }
        // 文件限制20M
        long size = file.getSize();
        if (size > MAX_POST_SIZE) {
            return Result.fail("文件最大为 20M！");
        }
        String folder = supplier.get() + PropertySlash.getSlash();
        log.info("文件上传地址：{}", folder);
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String path = folder + file.getOriginalFilename();
        log.info("文件详细路径：{}", folder);
        File files = new File(path);
        if (FileUtil.exist(files)) {
            return Result.fail("文件已存在");
        }
        File file1 = FileUtil.writeBytes(file.getBytes(), path);
        if (file1.length() < 0) {
            return Result.fail("文件上传失败");
        }
        return Result.succ(1, "成功", null);
    }


    @GetMapping("/reload/{fileName}")
    public ResponseEntity<Resource> reload(@PathVariable String fileName) {
        String filePath = supplier.get() + fileName;
        log.info("文件下载路径：{}", filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        try {
            InputStreamResource resource = new InputStreamResource(Files.newInputStream(file.toPath()));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return ResponseEntity.ok().headers(headers).body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        try {
            String filePath = supplier.get() + fileName;
            log.info("文件下载路径：{}", filePath);
            File file = new File(filePath);
            String filename = file.getName();
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            int read = fis.read(buffer);
            fis.close();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("文件下载失败：{}", ex.getMessage());
        }
    }

    private static final Supplier<String> supplier = () -> {
        String dir = System.getProperty("user.dir");
        return dir + "/file/";
    };
}
